// components/UploadImage/index.js
const {controller,baseUrl} = require('../../pages/controllers/controllers');


const app=getApp()

Component({
  /**
   * 组件的属性列表
   */
  properties: {
     visible:{
       type:Boolean,
       value:false
     },
     
     goodsId:{
      type:[String,Number],
      value:''
     },
     title:{
       type:String,
       value:''
     },
     imgSrc:{
       type:String,
       value:""
     }
  },

  
  /**
   * 组件的初始数据
   */
  data: {
      hidden:false
  },
  
  /**
   * 组件的方法列表
   */
  methods: {
  toggleVisible(){
   this.setData({
    visible:!this.data.visible
   },()=>{
     this.triggerEvent('toggle',this.data.visible)
   })
  },
  
   getCanvasImg(qrCode,fn){
   
    
    let that=this
    let query=wx.createSelectorQuery().in(this)
    console.log('query',query)
    query.select('#myCanvas').fields({ node: true, size: true })
    .exec( (res) => {
    
      const canvas = res[0].node
      console.log('canvas',canvas)
      const ctx = canvas.getContext('2d')
      const dpr = wx.getSystemInfoSync().pixelRatio
      canvas.width = res[0].width * dpr
      canvas.height = res[0].height * dpr
       console.log('res[0].height * dpr',res[0].height * dpr)
     
      ctx.scale(dpr,dpr)
      ctx.clearRect(0, 0,res[0].width * dpr,res[0].height * dpr)
      ctx.fillStyle='#fff'
       ctx.fillRect(0,0,res[0].width * dpr,res[0].height * dpr)
      
      //获取图片路径信息
      //
     that.drawCanvas(canvas,ctx,qrCode).then(res=>{
      this.setData({
        hidden:false
      })
    
      wx.hideLoading()
      typeof fn =='function'&&fn(res)
     }).catch(err=>{
    
      this.setData({
        hidden:false
      })
      wx.hideLoading()
     })
    
  
     
    
    })
   },

 drawCanvas(canvas,ctx,qrCode){
   console.log('drawCanvas',canvas)
   console.log('ctx',ctx)
try {
  return  new Promise(async (Resolve,Reject)=>{
  let that=this
   // 获取文宽度
   let textWidth=(text)=>{
    return canvas.measureText(text).width
  }
  // 获取图片路径
   let getImageInfo=(path)=>{
      console.log('getImageInfo',path)
    return  new Promise((resolve,reject)=>{
          wx.getImageInfo({
            src:path,
            success:function(res){
             resolve(res)
            },
            fail:function(err){
              Reject(err)
             return  wx.showToast({
                title: '图片获取失败',
                icon:'none'
              })
              
            }
          })
         })
     }
  // 获取图片对象
   let getCreateImage=(path,width,height)=>{
   
  return new Promise((resolve,reject)=>{
    console.log('canvas.createImage',canvas.createImage)
    let obj = canvas.createImage()
  
    obj.src=path
   
     obj.onload=()=>{
        resolve(obj)
     }
     obj.onerror=(err)=>{
      Reject(err)
       return wx.showToast({
         title: '生成图像失败',
         icon:'none'
       })
     }
   })
   }
   let allHeight=0,allWidth=0,width=0,height=0,x=0,y=0
    
  let res= await getImageInfo(that.data.imgSrc)
    
  let scale=res.width/res.height
  
   width=wx.getSystemInfoSync().screenWidth

   height=width/scale

   allWidth=width
   

  // 画图
  let image= await getCreateImage(res.path)
  console.log('image',image)
    ctx.drawImage(image,0,0,width,height)


   y=height+20 //10为外边距
   x=15
   ctx.fillStyle='#000'
   ctx.font=" 700 20px PingFangSC-Medium"
   ctx.fillText(that.data.title,x,y)
  //生成二维码
 


  y+=40
  res=await getImageInfo(qrCode)
  image= await getCreateImage(res.path)
  ctx.drawImage(image,width-60-15,y+10,60,60)
  //画图标
  y+=15
  res=await getImageInfo('https://636c-cloud1-1ghscnpr6968a29d-1310640567.tcb.qcloud.la/%E5%88%86%E4%BA%AB%E4%BA%8C%E7%BB%B4%E7%A0%81%E5%9B%BE%E7%89%87_logo%403x.png?sign=99716ed00c7a47b6917a2b86c4dcc843&t=1655957005')
  image= await getCreateImage(res.path)
  ctx.drawImage(image,x,y-2,24,24)
  

  
  
  ctx.fillStyle='#1A1A1A'
  ctx.font='600 16px PingFangSC-Semibold'
  ctx.fillText('LUCKIN SEVEN',x+8+24,y+16)
  y+=(24+5+20)
  ctx.fillStyle='#000000'
  ctx.font='14px PingFangSC-Semibold'
  ctx.fillText('长按扫描识别二维码即可选购',x,y)
  y+=15+10

  allHeight=y
  

  
    setTimeout(()=>{
      wx.canvasToTempFilePath({
        canvas,
        width:allWidth,
        height:allHeight,
        destWidth:allWidth*3,
        destHeight:allHeight*3,
        quality:1,
        fileType:'jpg',
        success:function(res){
        console.log('canvasToTempFilePath',res)
         Resolve(res.tempFilePath)
        },
        fail:function(err){
         Reject(err)
        return wx.showToast({
          title: '生成图片失败',
          icon:'none'
        })
        }
      })
    },1000)
  })   
  
} catch (error) {

  wx.hideLoading()
   wx.showToast({
    title: '生成图片失败',
    icon:'none'
  })
    return Promise.reject(Error)
}
  
 
   
    
   },

  save(){
    let pages = getCurrentPages() //获取加载的页面
    let path = pages[pages.length - 1].route
    
    console.log('path',path)
    
    let scene=`id=${this.data.goodsId}&parentid=${wx.getStorageSync('userInfo').id}`
    let goodsId=this.data.goodsId

   wx.showLoading({
     title: '上传中',
   })
   
    controller.makeQrCode({path,scene,goodsId}).then(res=>{
    
      if(res.code==0){
        this.setData({
          hidden:true
        })
        this.getCanvasImg(res.data.baseData,(path)=>{
          wx.navigateTo({
              url: '/pages/Detail/save?url='+path,
          })
         })

        this.toggleVisible()

       
      }else{
        wx.showToast({
          title: res.msg,
          icon:'none'
        })
      }
    }).catch(err=>{
      wx.hideLoading()
      wx.showToast({
        title:'获取二维码失败',
        icon:'none'
      })

    })
   
  },
  share(){
    this.toggleVisible()
  },
   

  }
})
